package com.huiminpay.merchant.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.common.cache.util.QRCodeUtil;
import com.huiminpay.merchant.common.SecurityUtil;
import com.huiminpay.merchant.convert.MerchantVoConver;
import com.huiminpay.merchant.dto.MerchantDTO;
import com.huiminpay.merchant.dto.StoreDTO;
import com.huiminpay.merchant.service.IMerchantService;
import com.huiminpay.merchant.service.ISmsService;
import com.huiminpay.merchant.vo.MchRegVo;
import com.huiminpay.merchant.vo.MerchantDetailVO;
import com.huiminpay.transaction.api.dto.QRCodeDto;
import com.huiminpay.transaction.service.ITransactionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

@Api(value = "商户操作",tags = {"商户"},description = "商户CRUD操作")
@RestController
public class MerchantController {
    @Reference
    IMerchantService merchantService;
    @Autowired
    ISmsService smsService;
    @Value("${aliyun.oss.domain}")
    private String domain;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Autowired
    OSS ossClient;
    @Reference
    ITransactionService transactionService;

    /**
     * 根据ID查询商户信息
     * @return
     */
    @ApiOperation(value = "根据ID查询商户信息")
    @GetMapping("findById")
    @ApiImplicitParam(paramType = "query",dataType = "Long",name = "id",value = "商户ID",required = true,defaultValue = "1")
    public MerchantDTO findMerchantById(@RequestParam Long id){
        return merchantService.findById(id);
    }

    @ApiOperation("获取登录用户的商户信息")
    @GetMapping(value="/my/merchants")
    public MerchantDTO getMyMerchantInfo(){
        // 从token 中获取商户id
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchant = merchantService.findById(merchantId);
        return merchant;
    }

    @ApiOperation("保存商户信息")
    @PostMapping("save")
    public MerchantDTO findMerchantById(@RequestBody MerchantDTO merchantDTO){

        return merchantDTO;
    }

    @ApiOperation("验证码发送")
    @GetMapping("/sms")
    public String sendSms(String mobile){
        return smsService.sendSms(mobile);
    }

    @ApiOperation("商户注册")
    @PostMapping("/merchants/register")
    public MerchantDTO regMch(@RequestBody MchRegVo mchRegVo){
        // 1.非空校验 TODO
        if(StringUtils.isEmpty(mchRegVo.getMobile())){
//            throw new RuntimeException("手机号不能为空");
            throw new BusinessException(CommonErrorCode.E_200230);
        }

        // 手机号格式校验
        if(!PhoneUtil.isMatches(mchRegVo.getMobile())){
            throw new BusinessException(CommonErrorCode.E_200224);
        }

        // 2. 验证码校验
        Boolean aBoolean = smsService.checkSmsCode(mchRegVo.getVerifiyCode(), mchRegVo.getVerifiykey());
        if(!aBoolean){
//            throw new RuntimeException("验证码已过期或者不存在");
            throw new BusinessException(CommonErrorCode.E_100102);
        }


        // 3.调用商户服务注册
        MerchantDTO merchantDTO = new MerchantDTO();
        BeanUtils.copyProperties(mchRegVo,merchantDTO);//属性拷贝


        return merchantService.regMerchant(merchantDTO);
    }


    @ApiOperation("文件上传")
    @PostMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file){
        if(file==null){
            throw new BusinessException(CommonErrorCode.E_200201);
        }
        //获取扩展名
        String originalFilename = file.getOriginalFilename();// xxx.xxx.x..x.png
        int i = originalFilename.lastIndexOf(".");//获取最后一个.的位置
        String extName = originalFilename.substring(i);

        //文件上传

        String path = UUID.randomUUID().toString().replace("-","")+extName;


        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,path , file.getInputStream());
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            System.out.println(putObjectResult.toString());

            return domain+path;

        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_200237);
        }

    }

    @ApiOperation("资质申请")
    @PostMapping("/my/merchants/save")
    public MerchantDetailVO apply(@RequestBody MerchantDetailVO merchantDetailVO){
        //没有商户ID如何获取
        Long merchantId = SecurityUtil.getMerchantId();

        // 对象转换
        MerchantDTO merchantDTO = MerchantVoConver.INSTANCE.VO2DTO(merchantDetailVO);
        merchantService.applyMerchant(merchantId,merchantDTO);

        return merchantDetailVO;
    }

    @PostMapping("/my/stores/merchants/page")
    public PageVO<StoreDTO> storeList(Integer pageNo,Integer pageSize){
        StoreDTO storeDTO = new StoreDTO();
        storeDTO.setMerchantId( SecurityUtil.getMerchantId());
        return merchantService.queryStoreByPage(storeDTO,pageNo,pageSize);
    }

    @GetMapping(value = "/my/apps/{appId}/stores/{storeId}/app-store-qrcode")
    public String createCScanBStoreQRCode(@PathVariable String appId, @PathVariable Long storeId) throws BusinessException {
        QRCodeDto qrCodeDto = new QRCodeDto();
        qrCodeDto.setStoreId(storeId);
        qrCodeDto.setAppId(appId);
        qrCodeDto.setMerchantId(SecurityUtil.getMerchantId());

        // 查询门店信息
        StoreDTO storeDTO= merchantService.queryStoreById(storeId);
        qrCodeDto.setSubject(storeDTO.getStoreName());
        qrCodeDto.setBody(storeDTO.getStoreName());
        String payUrl = transactionService.createStoreQRCode(qrCodeDto);

        QRCodeUtil qrCodeUtil = new QRCodeUtil();

        try {
            return qrCodeUtil.createQRCode(payUrl,200,200);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.CUSTOM);
        }
    }
}
